#!/usr/bin/python

import board
from random import choice

def rate_position_1(pos):
    """ Rate position
    based on score plus open rows
    """
    open_for_X, open_for_O = pos.count_patterns()
    rating = 0
    for k in range(board.size):
        rating += open_for_X[k] * 0.5 ** k
        rating -= open_for_O[k] * 0.5 ** k
    return rating

def rate_position_2(pos, col):
    """ Rate position
    based on score plus open rows
    take into account whose turn it is
    """
    open_for_X, open_for_O = pos.count_patterns()
    rating = 0
    fac_X = [0.5 ** k for k in range(board.size)]
    fac_O = fac_X[:]
    if pos.whose_turn == 1:
        fac_X[1] += 0.1
        fac_O[1] -= 0.1
    else:
        fac_X[1] -= 0.1
        fac_O[1] += 0.1
    for k in range(board.size):
        rating += open_for_X[k] * fac_X[k]
        rating -= open_for_O[k] * fac_O[k]
    return rating

def rate_position_2a(pos, col, a=0.5, b=0.5, c=0.25, d=0.25):
    """ Rate position
    based on score plus open rows
    take into account whose turn it is
    """
    open_for_X, open_for_O = pos.count_patterns()
    rating = 0
    fac_t = [1, a, c]
    fac_n = [1, b, d]
    if pos.whose_turn == 1:
        fac_X = fac_t
        fac_O = fac_n
    else:
        fac_X = fac_n
        fac_O = fac_t
    for k in range(board.size):
        rating += open_for_X[k] * fac_X[k]
        rating -= open_for_O[k] * fac_O[k]
    return rating

def computer_1_move(pos):
    """ Simple, but effective engine
    try out all moves and rate position
    """
    mc = pos.whose_turn # my colour
    value = [-len(board.rows) for k in range(board.board_size)]
    emsq = pos.find_empty_squares()
    for num in emsq:
        pos.set(num, mc)
        value[num] = rate_position_1(pos) * mc
        pos.set(num, 0)
    best = value.index(max(value))
    pos.move(best)

def computer_2_move(pos, a=0.5, b=0.5, c=0.25, d=0.25):
    """ Same as computer_1
    but use rate_position_2
    """
    mc = pos.whose_turn
    value = [-len(board.rows) for k in range(board.board_size)]
    emsq = pos.find_empty_squares()
    for num in emsq:
        pos.set(num, mc)
        value[num] = rate_position_2a(pos, mc * (-1),a,b,c,d) * mc
        pos.set(num, 0)
    best = value.index(max(value))
    pos.move(best)

def random_player(pos):
    """ Play random move
    """
    emsq = pos.find_empty_squares()
    pos.move(choice(emsq))
